package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DemoCountDown {

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch latch = new CountDownLatch(3);

		Task1 task1 = new Task1(latch);
		Task2 task2 = new Task2(latch);
		Task3 task3 = new Task3(latch);

		ExecutorService exec = Executors.newCachedThreadPool();
		exec.submit(task1);
		exec.submit(task2);
		exec.submit(task3);

		latch.await();// 只要大于0，就在此一直等待
		System.out.println(latch.getCount());

		exec.shutdown();
	}

}

class Task1 implements Runnable {

	private CountDownLatch latch;

	public Task1(CountDownLatch latch) {
		this.latch = latch;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(3 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "-->" + latch.getCount());
		latch.countDown();
	}
}

class Task2 implements Runnable {

	private CountDownLatch latch;

	public Task2(CountDownLatch latch) {
		this.latch = latch;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(1 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "-->" + latch.getCount());
		latch.countDown();
	}
}

class Task3 implements Runnable {

	private CountDownLatch latch;

	public Task3(CountDownLatch latch) {
		this.latch = latch;
	}

	@Override
	public void run() {
		try {
			Thread.sleep(5 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "-->" + latch.getCount());
		latch.countDown();
	}
}